package gfxlsx

import (
	"fmt"

	"github.com/gogf/gf/container/gvar"
	"github.com/gogf/gf/database/gdb"
	"github.com/tealeg/xlsx"
)

func ReadFile(filename, sheetname string) (gdb.Result, error) {
	f, err := xlsx.OpenFile(filename)
	if err != nil {
		return nil, err
	}
	sheet, ok := f.Sheet[sheetname]
	if !ok {
		return nil, fmt.Errorf("sheet %s not found", sheetname)
	}
	if len(sheet.Rows) < 2 {
		return nil, fmt.Errorf("数据行不能小于2")
	}
	var result gdb.Result
	headrow := sheet.Rows[0]
	head := make([]string, len(headrow.Cells))
	for i := 0; i < len(headrow.Cells); i++ {
		if headrow.Cells[i].Value == "" {
			head[i] = fmt.Sprintf("第%d列", i+1)
		} else {
			head[i] = headrow.Cells[i].Value
		}
	}
	fmt.Println(head)

	for i := 1; i < len(sheet.Rows); i++ {
		re := make(gdb.Record)
		for j := 0; j < len(headrow.Cells) && j < len(sheet.Rows[i].Cells); j++ {
			re[head[j]] = gvar.New(sheet.Rows[i].Cells[j].String())
		}
		result = append(result, re)
	}

	return result, nil
}
